#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>

/*多线程求平方和 */
int sum_sql(int n)
{
    sleep(1);
    return n * n;
}

void *cal_thread(void *arg)
{
    int n = *(int *)arg;
    int sqr = sum_sql(n);
    int *result = (int *)malloc(sizeof(int));
    *result = sqr;
    return result;
}
int main(int argc, char const *argv[])
{
    int items[5] = {1, 2, 3, 4, 5};
    int sqrs[5];
    int sum = 0;
    pthread_t ptr[5];
    struct timeval start, end;
    gettimeofday(&start, NULL);
    for (int i = 0; i < 5; i++)
    {
        pthread_create(ptr + i, NULL, cal_thread, &items[i]);
    }
    for (int i = 0; i < 5; i++)
    {
        void *result;
        pthread_join(ptr[i], &result);
        sqrs[i] = *(int *)result;
    }
    gettimeofday(&end, NULL);
    for (int i = 0; i < 5; i++)
    {
        sum += sqrs[i];
    }
    printf("sum: %d\n", sum);
    printf("运行时间: %ld秒\n", end.tv_sec - start.tv_sec);
    return 0;
}
